<template>
    <el-autocomplete v-model="model" :fetch-suggestions="remoteMethod" placeholder="请输入关键词" @select="handleSelect" :popper-class="textAlign" style="width:100%"></el-autocomplete>
</template>

<script>
import { getTeacherList } from 'api/cardManagement';

export default {
    props: {
        value: {
            type: [String, Number],
            required: true
        },
        schoolId: {
            type: [String, Number],
            required: true
        }
    },
    computed: {
        model: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val);
            }
        }
    },
    data() {
        return {
            list: null,
            teacherName: '',
            textAlign: ''
        }
    },
    created() {
        this.teacherName = this.value;
    },
    methods: {
        remoteMethod(query, cb) {
            query = query.trim();
            if (query =='') {
                cb([{value: '无数据'}]);
                this.textAlign = 'remote-center';
            }
            if (this.teacherName!=query && this.teacherName!='') {
                this.$emit('change', '');
            }
            if (query) {
                getTeacherList(this.schoolId, query).then(response => {
                    this.list = response.data.content;
                    //console.log('this.list', this.list);
                    if (this.list=='') {
                        this.textAlign = 'remote-center';
                        return;
                    }
                }).then(() => {
                    let results = this.list.filter(this.createStateFilter(query));
                    if (results.length) {
                        this.textAlign = '';
                        cb(results)
                    } else {
                        cb([{value: '无数据'}]);
                        this.textAlign = 'remote-center';
                    }
                });
            }  
        },
        createStateFilter(query) {
            return (state) => {
                state.value = state.sUserName; 
                return (state.value.toLowerCase().includes(query.toLowerCase()));
            };
        },
        handleSelect(val) {
            if (val.fUserId) {
                this.teacherName = val.sUserName; // 获取缓存学校名字
                this.$emit('change', val.fUserId);
                this.$emit('getStudentInfor', val);
            } else {
                this.$emit('input', '');
            }
        }
    }
}
</script>

<style>

</style>
